<?php
/**
 * Created by PhpStorm.
 * User: https://pingxonline.com/
 * Date: 2018-08-12
 * Time: 9:36
 */

include_once 'config.php';
include_once 'QQHelper.php';
include_once 'AvatarHelper.php';
include_once 'FileHelper.php';

if (!isset($_POST['qq'])){
    die("请输入QQ号码");
}

// 读取文件，若没有记录则获取新的cookies
$cookie = FileHelper::reader(config::$filename);

if (empty($cookie)){
    // 获取新cookies
    $cookie = get_cookies();
}

// 目标号码
$target_qq = test_input($_POST['qq']);

$result = null;

$count = 1;

do{
    // 获取头像
    $result = get_avatar($cookie, $target_qq);

    if (validation($result)){
        $count = config::$retry_time + $count;
        break;
    }else{
        if ($count > 2){
            $cookie = get_cookies();
        }
    }
    $count++;
}while($count <= config::$retry_time);

if ($result != null){
    if (validation($result)){
        // 时间戳转换
        $result = json_decode($result, true);
        for ($i =0; $i < count($result['file_list']); $i++){
            $result['file_list'][$i]['timestamp'] = date('Y-m-d',$result['file_list'][$i]['timestamp']);
        }
        echo json_encode($result);
    }else{
        echo json_encode(array('error'=>'服务器异常'));
    }

}else{
    echo "服务器异常请重试";
}



/**
 * @return mixed 返回cookies
 */
function get_cookies(){
    $QQHelper = new QQHelper();
    // 获取提取关键参数的数组，array ( 'uin' => '', 'skey' => '', )
    $cookie = $QQHelper->login(config::$server, config::$url, config::$qq, config::$password);
    //var_export($cookie);
    // 写入文件
    FileHelper::writer(config::$filename, $cookie);
    return $cookie;
}

/**
 * @param $cookie
 * @param $target_qq
 * @return mixed
 */
function get_avatar($cookie, $target_qq){
    // 实例化获取头像
    $avatar = new AvatarHelper();
    $result = $avatar->avatar($cookie, $target_qq);
    return $result;
}

/**
 * @param $result
 * @return bool 获取的头像是否正确
 */
function validation($result){
    if ($result){
        $data = json_decode($result, true);
        if ($data['ret']==0){
            // ret = 0 请求成功
            return true;
        }else{
            // 没有返回total_num总数属性，应该是cookies超时了，重新请求获取cookies
            // 错误返回
//            {
//                "ret" : -1
//            }
            return false;
        }

    }else{
        // $result 为false，访问超时
        return false;
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}